package org.jeecg.demo.wx.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.demo.wx.common.WXLoginUser;
import org.jeecg.demo.wx.common.WXUserContext;
import org.jeecg.demo.wx.common.WXUserInfo;
import org.jeecg.demo.wx.constant.CacheConstant;
import org.jeecg.demo.wx.util.WXJWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 功能描述
 * 小程序token验证切面实现类
 *
 * @author: zgq
 * @date: 2024年01月29日 16:20
 */
@Aspect
@Component
public class WXTokenAuthHandler {
    public static final Logger logger = LoggerFactory.getLogger(WXTokenAuthHandler.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtil redisUtil;

    @Around("@annotation(org.jeecg.demo.wx.aspect.WXTokenAuthAspect)")
    public Object tokenAuth(ProceedingJoinPoint pjp) throws Throwable {
        try {
            String token = request.getHeader("token");
            if (Objects.isNull(token)) {
                throw new RuntimeException("token不存在");
            }
            logger.info("token：{}", token);
            String openid = WXJWTUtil.getOpenid(token);
            WXLoginUser wxLoginUser = (WXLoginUser) redisUtil.get(CacheConstant.WX_USER_LOGIN_KEY + openid);
            if (!WXJWTUtil.verify(token, openid, wxLoginUser.getSessionKey())) {
                throw new RuntimeException("token非法");
            }
            WXUserContext.set(new WXUserInfo(openid, wxLoginUser.getSessionKey()));
            return pjp.proceed();
        } finally {
            WXUserContext.remove();
        }
    }
}
